<template>
  <div>
    <el-card>
      <div slot="header" class="clearfix">
        <el-button @click="back" icon="el-icon-arrow-left">返回</el-button>
        <span style="margin-left: 10px">{{
          ruleForm.id ? ($route.query.type == 1 ? '编辑课程' : '课程详情') : '新增课程'
        }}</span>
      </div>
      <el-form
        :model="ruleForm"
        style="width: 100%"
        :rules="rules"
        ref="ruleForm"
        label-width="70px"
        class="demo-ruleForm"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="课程名称" prop="course_name">
              <el-input
                :disabled="$route.query.type == 2"
                v-model="ruleForm.course_name"
                maxlength="50"
                show-word-limit
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="企业类型" prop="merchant_type_id">
              <el-select
                :disabled="$route.query.type == 2"
                style="width: 100%"
                v-model="ruleForm.merchant_type_id"
                placeholder="请选择"
              >
                <el-option v-for="(item, index) in merchantTypeList" :key="index" :label="item.name" :value="item.id">{{
                  item.name
                }}</el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="培训类型" prop="selected_type_ids">
              <el-cascader
                :disabled="$route.query.type == 2"
                :show-all-levels="false"
                :options="options2"
                style="width: 100%"
                v-model="ruleForm.selected_type_ids"
                :props="{ multiple: true, checkStrictly: true, label: 'title', value: 'id' }"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="课程类型" prop="course_type">
              <el-select
                :disabled="$route.query.type == 2"
                style="width: 100%"
                v-model="ruleForm.course_type"
                placeholder="请选择"
              >
               <el-option label="公共课" :value="1">公共课</el-option>
                <el-option label="专业课" :value="2">专业课</el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="选修类型" prop="require_type">
              <el-select
                :disabled="$route.query.type == 2"
                style="width: 100%"
                v-model="ruleForm.require_type"
                placeholder="请选择"
              >
                <el-option label="必修课" :value="1">必修课</el-option>
                <el-option label="选修课" :value="2">选修课</el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="课程介绍" prop="desc">
              <el-input
                :disabled="$route.query.type == 2"
                style="width: 100%"
                type="textarea"
                :autosize="{ minRows: 5 }"
                placeholder="请输入课程介绍"
                v-model="ruleForm.desc"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="课程图片" prop="img_url">
              <p class="prompt">格式JPG、PNG、JPGE</p>
              <el-upload
                v-if="$route.query.type != 2"
                class="avatar-uploader"
                action="#"
                :show-file-list="false"
                accept=".jpg, .png, .jpeg"
                :before-upload="beforeAvatarUpload"
                :http-request="handleAvatarSuccess"
              >
                <img v-if="ruleForm.img_url" :src="ruleForm.img_url" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
              <el-image
                style="width: 150px; height: 106px"
                v-if="$route.query.type == 2 && ruleForm.img_url"
                :src="ruleForm.img_url"
                :preview-src-list="[ruleForm.img_url]"
                class="avatar"
              >
              </el-image>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="课件" prop="ware_ids">
          <el-button
            v-if="$route.query.type != 2"
            type="primary"
            size="mini"
            style="flex-shrink: 0; margin-left: 10px"
            @click="addWare"
            >添加</el-button
          >
        </el-form-item>
      </el-form>
      <el-table
        :data="tableData"
        border
        empty-text="暂无数据"
        no-filtered-userFrom-text="暂无筛选结果"
        style="width: 100%; margin-bottom: 60px"
      >
        <el-table-column fixed type="index" align="center" label="序号" width="50" />
        <el-table-column fixed prop="title" align="center" show-overflow-tooltip label="课件名称" min-width="140" />
        <el-table-column prop="type_name" align="center" label="培训类型" min-width="140"></el-table-column>
        <el-table-column prop="resource_type" align="center" label="课件来源" min-width="100">
          <template #default="scope">
            <span v-if="scope.row.resource_type == 1">公共资源</span>
            <span v-else-if="scope.row.resource_type == 2">平台资源</span>
            <span v-else-if="scope.row.resource_type == 3">我的资源</span>
          </template>
        </el-table-column>
        <el-table-column prop="teacher_name" align="center" label="讲师姓名" min-width="120"></el-table-column>
        <el-table-column prop="duration" align="center" label="课长" min-width="100" />
        <el-table-column prop="create_time" align="center" label="创建时间" min-width="140"></el-table-column>
        <el-table-column
          v-if="$route.query.type != 2"
          fixed="right"
          align="center"
          prop="action"
          label="操作"
          width="160"
        >
          <template #default="scope">
            <div class="action">
              <span v-if="scope.$index != 0" @click="handleUp(scope)">上移</span>
              <span v-if="scope.$index != tableData.length - 1" @click="handleDown(scope)">下移</span>
              <span @click="delOk(scope)">删除</span>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <div class="footer" v-if="$route.query.type != 2">
      <el-button @click="back">关闭</el-button>
      <el-button type="primary" size="medium" @click="submitForm('ruleForm')">保存</el-button>
    </div>

    <!-- 选择课件 -->
    <el-dialog title="选择课件" :visible.sync="isShowAdd2" width="1200px" :before-close="handleClose2" :close-on-click-modal="false">
      <div class="head">
        <div class="input">
          <span>课件名称：</span>
          <el-input v-model="queryData2.title" placeholder="请输入" />
        </div>
        <div class="input">
          <span>培训类型：</span>
          <el-cascader
            :show-all-levels="false"
            :options="options2"
            v-model="queryData2.selected_type_ids"
            :props="{ multiple: true, checkStrictly: true, label: 'title', value: 'id' }"
            clearable
          ></el-cascader>
        </div>
        <div class="input" >
          <span>课程来源：</span>
          <el-select v-model="queryData2.resource_type" placeholder="请选择课件来源">
            <el-option label="公共课件" :value="1">公共课件</el-option>
            <el-option label="平台课件" :value="2">平台课件</el-option>
            <el-option label="我的课件" :value="3" v-if="this.$route.query.resource_type == 3">我的课件</el-option>
          </el-select>
        </div>
        <el-button type="primary" class="btn" @click="search2">查询</el-button>
        <el-button type="primary" class="btn" @click="reset2">重置</el-button>
      </div>
      <el-table
        :data="tableData2"
        border
        v-loading="isTableLoading"
        empty-text="暂无数据"
        no-filtered-userFrom-text="暂无筛选结果"
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column fixed type="selection" align="center" label="序号" width="50" />
        <el-table-column fixed prop="title" align="center" show-overflow-tooltip label="课件名称" min-width="160" />
        <el-table-column prop="type_name" align="center" label="培训类型" min-width="220"></el-table-column>
        <el-table-column prop="resource_type" align="center" label="课件来源" min-width="100">
          <template #default="scope">
            <span v-if="scope.row.resource_type == 1">公共资源</span>
            <span v-else-if="scope.row.resource_type == 2">平台资源</span>
            <span v-else-if="scope.row.resource_type == 3">我的资源</span>
          </template>
        </el-table-column>
        <el-table-column prop="teacher_name" align="center" label="讲师姓名" min-width="80"></el-table-column>
        <el-table-column prop="duration" align="center" label="课长" min-width="60" />
        <el-table-column prop="create_time" align="center" label="创建时间" min-width="140"></el-table-column>
      </el-table>
      <el-pagination
        background
        style="margin-top: 5px; text-align: right"
        @size-change="search2"
        @current-change="getWareList"
        :current-page.sync="queryData2.page"
        :page-size.sync="queryData2.size"
        layout="total, prev, pager, next,sizes,jumper"
        :total="total2"
      >
      </el-pagination>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose2">关闭</el-button>
        <el-button type="primary" @click="handleConfirmSelectWare">提交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { dateFormat } from '../../libs/util';
import { TrainTypeTree, SystemTypeMerchantType, upload, CourseWareList, CourseSave, CourseInfo } from '@/api/manage';
export default {
  name: 'addTeacher',
  data() {
    return {
      ruleForm: {
        course_name: '',
        merchant_type_id: '',
        type_ids: [],
        selected_type_ids: [],
        desc: '',
        ware_ids: [],
        img_url: '',
        course_type:1,
        require_type:1
      },
      rules: {
        course_name: [{ required: true, message: '请输入课程名称', trigger: 'blur' }],
        merchant_type_id: [{ required: true, message: '请选择企业类型', trigger: 'change' }],
        selected_type_ids: [{ required: true, message: '请选择培训类型', trigger: 'change' }],
        img_url: [{ required: true, message: '请上传课程图片', trigger: 'change' }],
        course_type: [{ required: true, message: '请选择课程类型', trigger: 'change' }],
        require_type: [{ required: true, message: '请选择选修类型', trigger: 'change' }],
        desc: [{ required: true, message: '请输入课程介绍', trigger: 'blur' }],
      },
      drawer: false,
      queryData: {
        name: '',
        type: '',
        teacher: '',
        page: 1,
        size: 10,
      },
      total: 0,
      isTableLoading: false,
      tableData: [],
      options2: [],
      merchantTypeList: [],
      queryData2: {
        title: '',
        page: 1,
        size: 10,
        exclude_ids: [],
        create_type: this.$route.query.create_type,
        selected_type_ids: [],
        type_ids: [],
        resource_type: Number(this.$route.query.resource_type),
      },
      tableData2: [],
      total2: 0,
      isShowAdd2: false,
      ware_ids: [],
    };
  },
  computed: {},
  created() {},
  mounted() {
    this.getTrainTypeTree();
    // this.getSystemTypeMerchantType();
    if (this.$route.query.id) {
      this.getInfo();
    }
    
    // 当create_type=2时，移除课程介绍和课程图片的必填验证
    if (this.$route.query.create_type === '2') {
      // 移除desc字段的required验证
      this.rules.desc = [];
      // 移除img_url字段的required验证  
      this.rules.img_url = [];
    }
  },
  watch: {
    'ruleForm.selected_type_ids': {
      handler(val) {
        this.ruleForm.type_ids = val.map((item) => item[item.length - 1]);
      },
      deep: true,
    },
    tableData: {
      handler(val) {
        // this.ruleForm.topic_ids = val.map(item => item.id).join(',');
        this.ruleForm.ware_ids = val.map((item) => item.id);
      },
      deep: true,
    },
    'queryData2.selected_type_ids'(newValue, oldValue) {
      if (this.queryData2.selected_type_ids.length > 0) {
        this.queryData2.type_ids = [];
        this.queryData2.selected_type_ids.forEach((item) => {
          this.queryData2.type_ids.push(item[item.length - 1]);
        });
      } else {
        this.queryData2.type_ids = [];
      }
    },
  },
  methods: {
    handleUp(scope) {
      if (scope.$index <= 0) return;
      this.tableData = [
        ...this.tableData.slice(0, scope.$index - 1),
        this.tableData[scope.$index],
        this.tableData[scope.$index - 1],
        ...this.tableData.slice(scope.$index + 1),
      ];
    },
    handleDown(scope) {
      if (scope.$index >= this.tableData.length - 1) return;
      this.tableData = [
        ...this.tableData.slice(0, scope.$index),
        this.tableData[scope.$index + 1],
        this.tableData[scope.$index],
        ...this.tableData.slice(scope.$index + 2),
      ];
    },
    getInfo() {
      CourseInfo({
        id: this.$route.query.id,
      }).then((res) => {
        this.ruleForm = JSON.parse(JSON.stringify(res.data.data));
        this.ruleForm.ware_ids = JSON.parse(this.ruleForm.ware_json);
        if (this.ruleForm.ware_ids?.length) {
          this.getWareInfo();
        }
      });
    },
    delOk(scope) {
      this.$confirm('确定删除该试题?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.tableData.splice(scope.$index, 1);
      });
    },
    handleConfirmSelectWare() {
      if (!this.ware_ids.length) {
        this.$message.error('请选择课题');
        return;
      }
      this.tableData = this.ware_ids.concat(this.tableData);
      this.handleClose2();
    },
    handleSelectionChange(val) {
      this.ware_ids = val;
    },
    handleClose2() {
      this.isShowAdd2 = false;
      this.queryData2 = {
        title: '',
        page: 1,
        size: 10,
        exclude_ids: [],
        create_type: this.$route.query.create_type,
      };
    },
    reset2() {
      this.queryData2 = {
        title: '',
        page: 1,
        size: 10,
        exclude_ids: [],
        create_type: this.$route.query.create_type,
        resource_type: Number(this.$route.query.resource_type),
      };
      this.getWareList();
    },
    search2() {
      this.queryData2.page = 1;
      this.getWareList();
    },
    addWare() {
      this.queryData2.exclude_ids = this.ruleForm.ware_ids || [];
      this.getWareList();
      this.isShowAdd2 = true;
    },
    close() {
      this.drawer = false;
    },
    remove(node, data) {
      const parent = node.parent;
      const children = parent.data.children || parent.data;
      let index = children.findIndex((item) => item.id == data.id);
      children.splice(index, 1);
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.ruleForm.create_type = this.$route.query.create_type;
          this.ruleForm.resource_type = this.$route.query.resource_type ?? ''; // 1是公共资源
          CourseSave(this.ruleForm).then((res) => {
            this.$message.success(this.ruleForm.id ? '修改成功' : '添加成功');
            this.back();
          });
        } else {
          this.$message.error('请正确填写！');
          return false;
        }
      });
    },
    handleAvatarSuccess(e) {
      let obj = new FormData();
      obj.append('file', e.file);
      upload(obj).then((res) => {
        this.ruleForm.img_url = res.data.url;
      });
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 5;
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 5MB!');
      }
      return isLt2M;
    },
    search() {
      this.queryData.page = 1;
      this.getWareList();
    },
    getWareList() {
      this.isTableLoading = true;
      this.queryData2.id = this.$route.query.id;
      let resource_type = this.$route.query.resource_type;
      if ( resource_type != 3 ) {
        // this.queryData2.resource_type = Number(resource_type);
      }
      CourseWareList(this.queryData2).then((res) => {
        this.tableData2 = res.data.list;
        this.total2 = res.data.total;
        this.isTableLoading = false;
      });
    },
    getWareInfo() {
      CourseWareList({
        id: this.$route.query.id,
        ids: this.ruleForm.ware_ids,
        create_type: this.$route.query.create_type,
        page: 1,
        size: this.ruleForm.ware_ids.length,
      }).then((res) => {
        this.tableData = res.data.list;
      });
    },
    getTrainTypeTree() {
      TrainTypeTree().then((res) => {
        this.options2 = res.data.list;
      });
    },
    getSystemTypeMerchantType() {
      SystemTypeMerchantType().then((res) => {
        this.merchantTypeList = res.data.list;
      });
    },
    back() {
      this.$router.back();
    },
  },
};
</script>

<style scoped>
.title {
  width: 100%;
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
.title > span {
  font-size: 14px;
  color: #000;
  font-weight: bold;
}
.avatar-uploader /deep/ .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 130px;
  height: 140px;
  display: flex;
  align-items: center;
}
.avatar-uploader /deep/ .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100%;
  line-height: 140px;
  text-align: center;
}
.avatar {
  width: 100%;
  display: block;
}
.prompt {
  font-size: 12px;
  color: red;
  margin-bottom: 5px;
}
.custom-tree-node {
  font-size: 12px;
  width: 100%;
  display: flex;
  align-items: center;
}
.index {
  padding: 0 5px;
  background: #eff0fd;
  line-height: 14px;
  color: #0256ff;
  border: 1px solid #84adff;
  border-radius: 2px;
  margin-right: 5px;
  font-size: 10px;
}
.el-icon-video-play,
.el-icon-document {
  margin-right: 5px;
}
.tree_btn {
  flex-shrink: 0;
  margin-left: auto;
}
.tree_btn /deep/ .el-button {
  font-size: 11px;
  padding: 5px 8px !important;
  margin-left: 10px !important;
}
.head {
  width: 100%;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}
.input {
  display: flex;
  align-items: center;
  margin-right: 15px;
  margin-bottom: 20px;
}
.input > span {
  font-size: 12px;
  flex-shrink: 0;
}
.btn {
  margin-bottom: 20px;
}
.footer {
  width: 100%;
  height: 60px;
  position: fixed;
  bottom: 0px;
  left: 0;
  z-index: 9;
  background: #ffffff;
  display: flex;
  align-items: center;
  justify-content: center;
  padding-left: 210px;
  border-top: 1px solid #e6e6e6;
}
.action {
  display: flex;
  align-items: center;
  justify-content: center;
}
.action span,
.look {
  color: #0256ff;
  font-size: 12px;
  cursor: pointer;
  margin: 0 8px;
}
</style>
